package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap;

import com.alibaba.cirtus.ots.application.adapter.ability.model.constant.GroupConstants;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.RequestUtils;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.result.Result;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.crb2btradecenter.api.orderquery.dto.QueryByOrderBizIdRequest;
import com.epoch.app.crb2btradecenter.sdo.OrderSDO;
import com.epoch.app.mnordercenter.model.dto.SalesOrderAtomCloseRequest;
import com.epoch.app.mnordercenter.orderbaserequest.OrderAtomUpdateRequest;
import com.epoch.app.mnordercenter.orderbaserequest.OrderLineAtomUpdateRequest;
import com.epoch.app.otsapplicationadaptersdk.model.dto.MnSapIfSORefusePOSNR;
import com.epoch.app.otsapplicationadaptersdk.model.dto.MnSapIfSORefuseRequest;
import com.epoch.app.otsapplicationadaptersdk.model.dto.MnSapIfSORefuseSDO;
import com.epoch.app.otsapplicationadaptersdk.sap.*;
import com.epoch.app.otsapplicationadaptersdk.sapv2.mnsapifsorefuse.dto.DoHandlerRequest;
import com.epoch.app.otsapplicationadaptersdk.sapv2.mnsapifsorefuse.service.MnSapIfSORefuseService;
import com.epoch.app.otsapplicationadaptersdk.service.ApiAdapterService;
import com.epoch.app.crb2btradecenter.api.orderquery.service.OrderQueryService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zhoubc
 * @description: 平台请求sap同步销售单拒绝
 * @date 2023/4/20 17:28
 */
@Component
@Primary
public class MnSapIfSORefuseServiceImpl implements MnSapIfSORefuseService {
    private final Log log = Log.getLogger(MnSapIfSORefuseServiceImpl.class);

    private final String MAIN_NOTE_CODE = "Z002";
    private final String LINE_NOTE_CODE = "Z013";
    private final String LANGU_CODE = "1";
    private final String ETENR_CODE = "0001";

    @Resource
    private ApiAdapterService apiAdapterService;
    @Resource
    private OrderQueryService orderQueryService;

    @Override
    @ProcessInvoker(remark = "MnSapIfSORefuseService", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public Object doHandler(DoHandlerRequest doHandlerRequest) {
        log.info("MnSapIfSORefuseServiceImpl_doHandler:{}",doHandlerRequest);
        List<SalesOrderAtomCloseRequest> batchCloseRequest = JSON.parseArray(doHandlerRequest.getMessage(), SalesOrderAtomCloseRequest.class);
        if (batchCloseRequest == null || CollectionUtils.isEmpty(batchCloseRequest)){
            log.info("MnSapIfSORefuseServiceImpl_doHandler_closeRequest_is_null");
            return Result.success(true);
        }
        log.info("MnSapIfSORefuseServiceImpl_batchCloseRequest:{}",JSONObject.toJSONString(batchCloseRequest));
        //判断是否是F-B的场景
        QueryByOrderBizIdRequest queryByOrderBizIdRequest = new QueryByOrderBizIdRequest();
        queryByOrderBizIdRequest.setOrderBizId(batchCloseRequest.get(0).getSalesOrderNo());
        log.info("MnSapIfSORefuseServiceImpl querySaleOrder req:{}",JSONObject.toJSONString(batchCloseRequest));
        OrderSDO saleOrderSDO = orderQueryService.queryByOrderBizId(queryByOrderBizIdRequest);
        log.info("MnSapIfSORefuseServiceImpl querySaleOrder rsp:{}",JSONObject.toJSONString(batchCloseRequest));
        if(Objects.nonNull(saleOrderSDO)){
            //todo 还需要兼容F-B-b场景。 一盘货不能使用orderCategoryCode(100，200，300的情况)&& F-B，东居，银虎
            boolean isF_B = isF_B(saleOrderSDO.getOrderCategoryCode()); //orderType
            boolean isF_BOf_FBb = isF_BOf_FBb(saleOrderSDO.getOrderCategoryCode(),saleOrderSDO.getOrderType());//都是300，分不清，有可能B-b
            if(isF_B || isF_BOf_FBb){
                OrderAtomUpdateRequest updateRequest = buildOrderAtomUpdateRequest(batchCloseRequest);
                //F-B场景走modify接口拒绝订单
                return reqSapSalesOrderModify(updateRequest);
            }
        }else{
            return "未查到销售单";
        }

        MnSapIfSORefuseRequest request = new MnSapIfSORefuseRequest();
        request.setMessageHeader(RequestUtils.generateMessageHeader("MNKA_SORefuse","ZT_OMC","ECC"));
        List<MnSapIfSORefuseSDO> data = new ArrayList<>();
        for (SalesOrderAtomCloseRequest closeRequest : batchCloseRequest) {
            MnSapIfSORefuseSDO sdo = new MnSapIfSORefuseSDO();
            sdo.setVBELN(closeRequest.getOutOrderNo());
            sdo.setPOSNR(Lists.newArrayList(MnSapIfSORefusePOSNR.builder().ITEM_NO(closeRequest.getOutLineNum()).build()));
            sdo.setABGRU(closeRequest.getCloseCode());
            data.add(sdo);
        }
        request.setData(data);

        return apiAdapterService.reqSapSalesOrderRefuse(request);
    }

    private boolean isF_B(String orderCategoryCode) {
        //集团订单
        if (Objects.equals(GroupConstants.ORDER_CATEGORY_CODE_GROUP, orderCategoryCode)) {
            return true;
        }
        return false;
    }

    private boolean isF_BOf_FBb(String orderCategoryCode,String orderTypeCode) {
        if (Objects.equals(GroupConstants.ORDER_CATEGORY_CODE_ONE_STOCK ,orderCategoryCode)) {
            if (Objects.equals(GroupConstants.ORDER_TYPE_F_B, orderTypeCode)) {
                return true;
            }
            return false;
            }
        return false;
    }

    private OrderAtomUpdateRequest buildOrderAtomUpdateRequest(List<SalesOrderAtomCloseRequest> batchCloseRequest){
        OrderAtomUpdateRequest updateRequest = new OrderAtomUpdateRequest();
        updateRequest.setSalesOrderNo(batchCloseRequest.get(0).getSalesOrderNo());
        updateRequest.setOutOrderNo(batchCloseRequest.get(0).getOutOrderNo());
        updateRequest.setModifierCode(batchCloseRequest.get(0).getModifierCode());
        updateRequest.setModifierName(batchCloseRequest.get(0).getModifierName());
        List<OrderLineAtomUpdateRequest> orderDetails = new ArrayList<>();
        batchCloseRequest.stream().forEach(salesOrderAtomCloseRequest -> {
            OrderLineAtomUpdateRequest orderLineAtomUpdateRequest = new OrderLineAtomUpdateRequest();
            orderLineAtomUpdateRequest.setCloseCode(salesOrderAtomCloseRequest.getCloseCode());
            orderLineAtomUpdateRequest.setLineNum(salesOrderAtomCloseRequest.getLineNum());
            orderLineAtomUpdateRequest.setOutLineNum(salesOrderAtomCloseRequest.getOutLineNum());
            orderDetails.add(orderLineAtomUpdateRequest);
        });
        updateRequest.setOrderDetails(orderDetails);
        return updateRequest;
    }


    private Object reqSapSalesOrderModify(OrderAtomUpdateRequest updateRequest){
        MnSapIfSOModifyRequest request = new MnSapIfSOModifyRequest();
        request.setMessageHeader(RequestUtils.generateMessageHeader("SaleOrder_CHANGE","ZT_OMC","ECC"));
        MnSapIfSOModifyHeadSDO headSDO = new MnSapIfSOModifyHeadSDO();
        List<MnSapIfSOModifyItemSDO> item2_item = new ArrayList<>();
        List<MnSapIfSOModifyScheduleSDO> item3_schedule = new ArrayList<>();
        List<MnSapIfSOModifyTextSDO> item4_text = new ArrayList<>();
        headSDO.setVBELN(updateRequest.getOutOrderNo());

        for (OrderLineAtomUpdateRequest updateLineRequest : updateRequest.getOrderDetails()) {
            MnSapIfSOModifyItemSDO itemSDO = new MnSapIfSOModifyItemSDO();
            itemSDO.setVBELN(updateRequest.getOutOrderNo());
            itemSDO.setPOSNR(updateLineRequest.getOutLineNum());
            itemSDO.setABGRU(updateLineRequest.getCloseCode());
            //不可为空item2_item，影响行备注sap修改是否成功
            item2_item.add(itemSDO);
        }
        headSDO.setItem2_item(item2_item);
        headSDO.setItem3_schedule(item3_schedule);
        headSDO.setItem4_text(item4_text);
        request.setItem1_head(headSDO);
        log.info("F-B的refuse reqSapSalesOrderModify:{}", JSONObject.toJSONString(request));
        return apiAdapterService.reqSapSalesOrderModify(request);
    }


}
